<template>
  <div class="app-container">
      <div style="display: flex;flex-direction: row;justify-content:space-between;align-items: center">
        <div style="height: 60px">
          <el-form :inline="true" :model="listQuery" size="small">
            <el-form-item label="姓名：">
              <el-input v-model="listQuery.userName" class="input-width" placeholder="昵称/姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="电话号码：">
              <el-input v-model="listQuery.mobile" class="input-width" placeholder="电话号码" clearable></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div  style="height: 60px">
          <el-button
            type="primary"
            @click="handleSearchList()"
            size="small">
            查询搜索
          </el-button>
          <el-button
            @click="handleResetSearch()"
            size="small">
            重置
          </el-button>
        </div>
      </div>
    <div class="table-container">
      <el-table ref="adminTable"
                :data="list"
                style="width: 100%;"
                v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="头像" align="center">
          <template slot-scope="scope">
            <img v-if="scope.row.avatar" class="user-avatar" :src="scope.row.avatar">
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="昵称" align="center">
          <template slot-scope="scope">{{scope.row.userName}}</template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">{{scope.row.realName}}</template>
        </el-table-column>
        <el-table-column label="电话" align="center">
          <template slot-scope="scope">{{scope.row.mobile}}</template>
        </el-table-column>
      <!--  <el-table-column label="性别" align="center">
          <template slot-scope="scope">{{scope.row.sex}}</template>
        </el-table-column>-->
        <el-table-column label="注册时间" width="160" align="center">
          <template slot-scope="scope">{{scope.row.createTime | formatDateTime}}</template>
        </el-table-column>
        <el-table-column label="状态" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="0"
              :inactive-value="1"
              active-text="启动"
              inactive-text="禁用"
              v-model="scope.row.activeStatus">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="text"
                       @click="handleSelectPower(scope.$index, scope.row)">分配权限
            </el-button>
         <!--   <el-button size="mini"
                       type="text"
                       @click="handleUpdate(scope.$index, scope.row)">
              重置密码
            </el-button>-->
          <!--  <el-button size="mini"
                       type="text"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="isEdit?'编辑用户':'添加用户'"
      :visible.sync="dialogVisible"
      width="40%">
      <el-form :model="admin"
               ref="adminForm"
               label-width="150px" size="small">
        <el-form-item label="帐号：">
          <el-input v-model="admin.username" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input v-model="admin.nickName" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：">
          <el-input v-model="admin.email" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="密码：">
          <el-input v-model="admin.password"  type="password" style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="admin.note"
                    type="textarea"
                    :rows="5"
                    style="width: 250px"></el-input>
        </el-form-item>
        <el-form-item label="是否启用：">
          <el-radio-group v-model="admin.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配权限"
      :visible.sync="powerDialogVisible"
      width="30%">
      <el-select v-model="havePowerIDArr" multiple
                 placeholder="请选择" size="small" style="width: 80%">
        <el-option
          v-for="item in allPowerList" :key="item.id+''"
          :label="item.powerName"
          :value="item.id+''">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="powerDialogVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="confirmSetUserPower()" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {userList,updateActiveStatus,
    updateUserPower,getHavePowerList,getAllPowerList} from '@/api/imUser';
  import {formatDate} from '@/utils/date';

  const defaultListQuery = {
    pageNum: 1,
    pageSize: 10,
    keyword: null
  };
  const defaultAdmin = {
    id: null,
    username: null,
    password: null,
    nickName: null,
    email: null,
    note: null,
    status: 1
  };
  export default {
    name: 'userIndex',
    data() {
      return {
        listQuery: Object.assign({
          userName:'',
          mobile:''
        }, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        dialogVisible: false,
        admin: Object.assign({}, defaultAdmin),
        isEdit: false,
        powerDialogVisible: false,
        havePowerIDArr:[],
        allPowerList:[],
        currentUserId:null
      }
    },
    created() {
      this.getList();
      this.getAllPowerList();
    },
    filters: {
      formatDateTime(time) {
        if (time == null || time === '') {
          return 'N/A';
        }
        let date = new Date(time);
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      }
    },
    methods: {
      handleResetSearch() {
        this.listQuery = Object.assign({
          userName: '',
          mobile: '',
        }, defaultListQuery);
        this.handleSearchList();
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      handleAdd() {
        this.dialogVisible = true;
        this.isEdit = false;
        this.admin = Object.assign({},defaultAdmin);
      },
      handleStatusChange(index, row) {
        this.$confirm('是否要改变启用/禁用状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log("row.activeStatus",row.activeStatus);
          updateActiveStatus(row.id, {activeStatus: row.activeStatus}).then(response => {
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消修改'
          });
          this.getList();
        });
      },
      handleDelete(index, row) {
        this.$confirm('是否要删除该用户?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAdmin(row.id).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        });
      },
      handleUpdate(index, row) {
        this.dialogVisible = true;
        this.isEdit = true;
        this.admin = Object.assign({},row);
      },
      handleDialogConfirm() {
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (this.isEdit) {
            updateAdmin(this.admin.id,this.admin).then(response => {
              this.$message({
                message: '修改成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          } else {
            createAdmin(this.admin).then(response => {
              this.$message({
                message: '添加成功！',
                type: 'success'
              });
              this.dialogVisible =false;
              this.getList();
            })
          }
        })
      },
      confirmSetUserPower(){
        this.$confirm('是否要确认?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = new URLSearchParams();
          params.append("userId", this.currentUserId);
          params.append("powerIDArr", this.havePowerIDArr);
          console.log(" this.havePowerIDArr", this.havePowerIDArr);
          updateUserPower(params).then(response => {
            this.$message({
              message: '分配成功！',
              type: 'success'
            });
            this.powerDialogVisible = false;
          })
        })
      },
      handleSelectPower(index,row){
        this.currentUserId = row.id;
        this.powerDialogVisible = true;
        this.getHavePowerList(row.id);
      },
      getList() {
        this.listLoading = true;
        console.log("查询条件",this.listQuery);
        userList(this.listQuery).then(response => {
          this.listLoading = false;
          this.list = response.data.list;
          this.total = response.data.total;
        });
      },
      getAllPowerList() {
        this.allPowerList=[];
        getAllPowerList().then(response => {
          let list = response.data;
          for (let i = 0; i < list.length; i++) {
              let id= list[i].id+"";
              let name=list[i].powerName;
              let obj={id:id, powerName:name};
              this.allPowerList.push(obj);
          }
          console.log("所有的权限",this.allPowerList);
        });
      },
      getHavePowerList(userId) {
        getHavePowerList(userId).then(response => {
          let powerList = response.data;
          this.havePowerIDArr=[];
          if(powerList!=null&&powerList.length>0){
            for(let i=0;i<powerList.length;i++){
              let powerId=powerList[i].powerId+'';
              this.havePowerIDArr.push(powerId);
            }
            console.log("this.havePowerIDArr", this.havePowerIDArr);
          }
        });
      }
    }
  }
</script>
<style scoped>
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 2px;
}
</style>


